package cn.xw.websocket.config;

import cn.xw.websocket.handler.StudentHandler;
import cn.xw.websocket.handler.TeacherHandler;
import cn.xw.websocket.interceptors.MyWebSocketInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * WebSocket配置类
 *
 * @author AnHui OuYang
 * @version 1.0
 */
@Configuration      //  代表当前是一个配置类
@EnableWebSocket    //  开启WebSocket的自动配置
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketConfigurer {

    // 注入属性（这里使用构造器注入，配合@RequiredArgsConstructor注解）
    private final StudentHandler studentHandler;
    private final TeacherHandler teacherHandler;
    private final MyWebSocketInterceptor myWebSocketInterceptor;

    /***
     * registerWebSocketHandlers方法用于注册WebSocket处理程序
     * @param registry 配置信息类
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                // 注册两个路径映射，并设置每个路径对应的处理器（这里我们就可以理解是多个Controller，路径不一样）
                .addHandler(studentHandler, "/ws/studentHandler/**")
                .addHandler(teacherHandler, "/ws/teacherHandler/**")
                // 设置允许跨域访问
                .setAllowedOrigins("*")
                // 添加WebSocket握手拦截器(后面需要实现)
                .addInterceptors(myWebSocketInterceptor);
    }
}
